package com.xszx.file.controller;

import com.xszx.server.dto.AjaxJson;
import com.xszx.server.entity.UploadFile;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

@RestController
public class UpLoadController {
    @Value("${file.path}")
    private String FILE_PATH;//物理路径

    @Value("${file.domain}")
    private String DOMAIN_PATH;//访问路径
    //进行文件的上传
    @PostMapping("/upload")
    public AjaxJson uploadOne(@RequestBody  MultipartFile file) throws IOException {
        //文件名称
        String fileName = file.getOriginalFilename();
        //文件大小
        int size = (int) file.getSize();

        System.out.println(fileName + "-->" + size);

        //指定文件的传输路径
        File fullDir = new File(FILE_PATH + fileName);

        if(!fullDir.getParentFile().exists()){ //判断文件父目录是否存在
            fullDir.getParentFile().mkdirs();
        }
        //进行文件的保存
        file.transferTo(fullDir);

        UploadFile uploadFile = new UploadFile();
        uploadFile.setPath(DOMAIN_PATH+fileName);
        uploadFile.setName(fileName);
        uploadFile.setSize(size);
        return AjaxJson.success().put("uploadFile",uploadFile);
    }
}
